package com.tech.service;

import cn.hutool.core.bean.BeanUtil;
import com.tech.model.DocModelField;
import com.tech.model.TemplateEntity;
import com.tech.utils.FieldConvertor;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import com.tech.model.GeneratorResult;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zouyao on 2023/06/04
 */
public abstract class Processor implements FieldConvertor {

    abstract Map<String/**sheetInfo*/, List<DocModelField>/**fieldInfo*/ > readMetaData(File file);

    abstract List<GeneratorResult> fillInfo(Map<String, List<DocModelField>> metaData,List<TemplateEntity> templateList);

    public List<GeneratorResult> process(File file, List<TemplateEntity> templateList) {
        Map<String, List<DocModelField>> metaData = readMetaData(file);
        List<GeneratorResult> results = fillInfo(metaData, templateList);
        return results;
    }

    /**
     * 根据模版格式化数据
     * @return
     */
    protected String fillTemplate(Template template ,Object v){
        try {
            Map<String, Object> dataMap = BeanUtil.beanToMap(v);
            Map convert = convert(dataMap);
            StringWriter writer = new StringWriter();
            template.process(convert, writer);
            return writer.toString();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return null;
        }
    }

}
